import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { useNavigate } from 'react-router-dom';

interface User {
  id: string;
  username: string;
  role: string;
  avatar?: string;
}

// 待审核用户接口
interface PendingUser {
  id: string;
  username: string;
  password: string;
  name: string;
  email: string;
  phone: string;
  department: string;
  position: string;
  registerTime: string;
  status: 'pending' | 'approved' | 'rejected';
}

interface AuthContextType {
  isAuthenticated: boolean;
  user: User | null;
  pendingUsers: PendingUser[];
  login: (username: string, password: string) => Promise<boolean>;
  register: (userData: any) => Promise<boolean>;
  logout: () => void;
  checkAuth: () => boolean;
  approveUser: (userId: string) => Promise<boolean>;
  rejectUser: (userId: string) => Promise<boolean>;
  getPendingUsers: () => PendingUser[];
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

interface AuthProviderProps {
  children: ReactNode;
}

// 模拟用户数据
const mockUsers = [
  { id: '1', username: 'admin', password: 'admin123', role: 'admin', avatar: '管' },
  { id: '2', username: 'user', password: 'user123', role: 'user', avatar: '赵' },
];

export function AuthProvider({ children }: AuthProviderProps) {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [user, setUser] = useState<User | null>(null);
  const [pendingUsers, setPendingUsers] = useState<PendingUser[]>([]);
  const navigate = useNavigate();

  // 模拟用户数据
  const mockUsers = [
    { id: '1', username: 'admin', password: 'admin123', role: 'admin', avatar: '管' },
    { id: '2', username: 'user', password: 'user123', role: 'user', avatar: '赵' },
  ];

  // 检查本地存储的认证状态
  useEffect(() => {
    const checkAuthStatus = () => {
      const savedAuth = localStorage.getItem('isAuthenticated');
      const savedUser = localStorage.getItem('user');
      
      if (savedAuth === 'true' && savedUser) {
        try {
          const userData = JSON.parse(savedUser);
          setIsAuthenticated(true);
          setUser(userData);
        } catch (error) {
          // 如果解析失败，清除本地存储
          localStorage.removeItem('isAuthenticated');
          localStorage.removeItem('user');
        }
      }
    };

    // 加载待审核用户数据
    const loadPendingUsers = () => {
      const savedPendingUsers = localStorage.getItem('pendingUsers');
      if (savedPendingUsers) {
        try {
          setPendingUsers(JSON.parse(savedPendingUsers));
        } catch (error) {
          localStorage.removeItem('pendingUsers');
        }
      }
    };

    checkAuthStatus();
    loadPendingUsers();
  }, []);

  const login = async (username: string, password: string): Promise<boolean> => {
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 500));
    
    const foundUser = mockUsers.find(u => u.username === username && u.password === password);
    
    if (foundUser) {
      const userData: User = {
        id: foundUser.id,
        username: foundUser.username,
        role: foundUser.role,
        avatar: foundUser.avatar
      };
      
      setIsAuthenticated(true);
      setUser(userData);
      localStorage.setItem('isAuthenticated', 'true');
      localStorage.setItem('user', JSON.stringify(userData));
      return true;
    }
    
    return false;
  };

  const logout = () => {
    setIsAuthenticated(false);
    setUser(null);
    localStorage.removeItem('isAuthenticated');
    localStorage.removeItem('user');
    navigate('/login');
  };

  const register = async (userData: any): Promise<boolean> => {
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 500));
    
    // 检查用户名是否已存在
    const existingUser = mockUsers.find(u => u.username === userData.username);
    if (existingUser) {
      return false;
    }
    
    // 创建待审核用户
    const pendingUser: PendingUser = {
      id: Date.now().toString(),
      username: userData.username,
      password: userData.password,
      name: userData.name,
      email: userData.email,
      phone: userData.phone,
      department: userData.department,
      position: userData.position,
      registerTime: new Date().toISOString(),
      status: 'pending'
    };
    
    // 保存到本地存储
    const updatedPendingUsers = [...pendingUsers, pendingUser];
    setPendingUsers(updatedPendingUsers);
    localStorage.setItem('pendingUsers', JSON.stringify(updatedPendingUsers));
    
    return true;
  };

  const checkAuth = (): boolean => {
    return isAuthenticated;
  };

  const approveUser = async (userId: string): Promise<boolean> => {
    await new Promise(resolve => setTimeout(resolve, 500));
    
    const userIndex = pendingUsers.findIndex(u => u.id === userId);
    if (userIndex === -1) return false;
    
    const approvedUser = pendingUsers[userIndex];
    
    // 添加到正式用户
    const newUser = {
      id: approvedUser.id,
      username: approvedUser.username,
      password: approvedUser.password,
      role: 'user',
      avatar: approvedUser.name.charAt(0)
    };
    mockUsers.push(newUser);
    
    // 更新待审核用户列表
    const updatedPendingUsers = pendingUsers.filter(u => u.id !== userId);
    setPendingUsers(updatedPendingUsers);
    localStorage.setItem('pendingUsers', JSON.stringify(updatedPendingUsers));
    
    return true;
  };

  const rejectUser = async (userId: string): Promise<boolean> => {
    await new Promise(resolve => setTimeout(resolve, 500));
    
    const updatedPendingUsers = pendingUsers.filter(u => u.id !== userId);
    setPendingUsers(updatedPendingUsers);
    localStorage.setItem('pendingUsers', JSON.stringify(updatedPendingUsers));
    
    return true;
  };

  const getPendingUsers = (): PendingUser[] => {
    return pendingUsers;
  };

  const value: AuthContextType = {
    isAuthenticated,
    user,
    pendingUsers,
    login,
    register,
    logout,
    checkAuth,
    approveUser,
    rejectUser,
    getPendingUsers,
  };

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  );
}

export function useAuth() {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
}
